package cn.supermarket.system.service.impl;

import cn.supermarket.common.utils.CaffeineUtils;
import cn.supermarket.common.utils.DictUtils;
import cn.supermarket.common.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.supermarket.common.entity.system.SysDictData;
import cn.supermarket.system.service.SysDictDataService;
import cn.supermarket.system.mapper.SysDictDataMapper;
import com.github.benmanes.caffeine.cache.LoadingCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 *
 */
@Service
public class SysDictDataServiceImpl extends ServiceImpl<SysDictDataMapper, SysDictData>
    implements SysDictDataService{
    @Autowired
    private LoadingCache dictCache;


    /**
     * 根据字典类型查询字典数据信息
     *
     * @param dictType
     */
    @Override
    public List<SysDictData> selectDictDataByType(String dictType) {
        List<SysDictData> dictDatas = (List<SysDictData>) CaffeineUtils.get(dictCache, DictUtils.getKey(dictType));
        if (StringUtils.isNotEmpty(dictDatas))
        {
            return dictDatas;
        }
        QueryWrapper<SysDictData> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("dict_type",dictType);
        dictDatas = this.baseMapper.selectList(queryWrapper);
        if (StringUtils.isNotEmpty(dictDatas))
        {
            CaffeineUtils.put(dictCache,dictType, dictDatas);
            return dictDatas;
        }
        return null;
    }

    /**
     * 批量删除字典数据信息
     *
     * @param dictCodes 需要删除的字典数据ID
     */
    @Override
    public void deleteDictDataByIds(Long[] dictCodes) {
        for (Long dictCode : dictCodes)
        {
            SysDictData data = selectDictDataById(dictCode);
            this.baseMapper.deleteById(dictCode);
            QueryWrapper<SysDictData> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("dict_type",data.getDictType());
            List<SysDictData> dictDatas = this.baseMapper.selectList(queryWrapper);
            CaffeineUtils.put(dictCache,data.getDictType(), dictDatas);
        }
    }

    /**
     * 根据字典数据ID查询信息
     *
     * @param dictCode 字典数据ID
     * @return 字典数据
     */
    @Override
    public SysDictData selectDictDataById(Long dictCode)
    {
        return this.baseMapper.selectById(dictCode);
    }

    /**
     * 根据条件分页查询字典数据
     *
     * @param dictData 字典数据信息
     * @return 字典数据集合信息
     */
    @Override
    public List<SysDictData> selectDictDataList(SysDictData dictData) {
        return this.baseMapper.selectDictDataList(dictData);
    }
}




